package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"errors"
)

type User struct {
	Id            int    `orm:"column(id);auto" json:"id,omitempty"`
	Account       string `orm:"column(account);null" json:"account,omitempty"`
	Password      string `orm:"column(password);null" json:"-"`
	MachineCode   string `orm:"column(machine_code);null" json:"machine_code,omitempty"`
	Allowed       int    `orm:"column(allowed);null" json:"allowed,omitempty"`
	Ip            string `orm:"column(ip);null" json:"ip,omitempty"`
	Level         int    `orm:"column(level);null" json:"level,omitempty"`
	CreateUid     int    `orm:"column(create_uid);null" json:"create_uid,omitempty"`
	RegisterTime  int64  `orm:"column(register_time);null" json:"register_time,omitempty"`
	UpdateTime    int64  `orm:"column(update_time);null" json:"update_time,omitempty"`
	AvailableTime int64  `orm:"column(available_time);null" json:"available_time,omitempty"`
	Token string `orm:"-" json:"token,omitempty"`
}
type UserList struct {
	Id            int    `orm:"column(id);auto" json:"id,omitempty"`
	Account       string `orm:"column(account);null" json:"account,omitempty"`
	}

type UserData struct {
	Account     string `json:"account"`
	Password    string `json:"password"`
	NewPassword string `json:"new_password"`
	CreateId    int `json:"create_id"`
	Uid         int    `json:"-"`
}

func (t *User) TableName() string {
	return "user"
}

func init() {
	orm.RegisterModel(new(User))
}

//检测用户名是否被注册
func WhetherTheUserExists(user *User) bool {
	o := orm.NewOrm()
	if err := o.Read(user, "account"); err != nil {
		return false
	}
	return true
}

// DeleteUser deletes User by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUser(id int) (err error) {
	o := orm.NewOrm()
	v := User{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&User{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	} else {
		err = errors.New("没有找到该用户")
	}
	return
}

func DeleteMachineCode(id int) (err error) {
	o := orm.NewOrm()
	v := User{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		if len(v.MachineCode) <= 0 {
			err = errors.New("该用户未绑定机器码")
			return
		}
		v.MachineCode = ""
		_, err = o.Update(&v, "machine_code")
		return
	} else {
		err = errors.New("没有找到该用户")
	}
	return
}

func AddTime(id int, t int64) (err error) {
	o := orm.NewOrm()
	v := User{Id: id}
	if err = o.Read(&v); err == nil {
		v.AvailableTime = v.AvailableTime + t
		_, err = o.Update(&v, "available_time")
		return
	} else {
		err = errors.New("没有找到该用户")
	}
	return
}

func ChangeLoginType(id int) (err error) {
	o := orm.NewOrm()
	v := User{Id: id}
	if err = o.Read(&v); err == nil {
		if v.Allowed == 1 {
			v.Allowed = 2
		} else if v.Allowed == 2 {
			v.Allowed = 1
		}
		_, err = o.Update(&v, "allowed")
		return
	} else {
		err = errors.New("没有找到该用户")
	}
	return
}
